//= require "list"
//= require "listview_grouped"

/* MusicNet Alignment Tool
 *
 * Copyright (c) 2010 Joe Lambert
 * 
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *  
 */

/** section: alignment
 * class GroupedList < ListContainer
 * 
 * Specialised container for list of Grouped items 
 **/

var GroupedList = new Class.create(ListContainer, {
	initialize: function($super, options)
	{
		this.tag = "grp";
		this.id = "groupedlist";
		this.verified = true;
		$super(options);
		
		this.toggle = Builder.node('ul', {className: 'toggle'}, [
			Builder.node('li', {className: 'verified first selected'}, 'Verified'),
			Builder.node('li', {className: 'unverified last'}, 'Un-verified')
		]);
		
		this.toggle.observe('click', function(event){
			event.stop();
			this.toggleVerified();
		}.bindAsEventListener(this));
		
		this.bodyDiv.insert(this.toggle);
		
		document.observe('group:added', function(event){
			if(event && event.memo)
			{
				var data = event.memo;
				
				for(var i=0; i<data.length; i++)
				{
					if(this.currentPage == data[i].items[0].a2z)
					{
						this.data.push({
							id: data[i].match_id,
							label: data[i].items[0].label,
							items: data[i].items
						});
					
						this.data.sort(function(a, b){
							return b.label < a.label;
						});
					
						this.listView.render();
						this.listView.scrollToID(data[i].match_id);
						//this.listView.addGroup(data.match_id, data.items);
					}					
				}

			}
		}.bindAsEventListener(this));
	},

/**
 * GroupedList#toggleVerified() -> null
 * 
 * Toggle the visibility of verified items
 **/
	
	toggleVerified: function()
	{
		var selected = this.toggle.getElementsBySelector(".selected")[0];
		
		if(selected.hasClassName('verified'))
		{
			this.verified = false;
			selected.removeClassName('selected');
			this.toggle.getElementsBySelector(".unverified")[0].addClassName('selected');
		}
		else
		{
			this.verified = true;
			selected.removeClassName('selected');
			this.toggle.getElementsBySelector(".verified")[0].addClassName('selected');
		}
		
		this.loadData(this.currentPage);
	},

/**
 * GroupedList#loadData(page, callback) -> null
 * - page (String): The A2Z page to load
 * - callback (function): The function to perform once the load has completed
 * 
 * Load the items from the given page
 **/
	
	loadData: function(page, callback)
	{
		this.listView.setLoading();
		this.updateA2Z();
		
		new Ajax.Request(window.location.pathname+this.options.dataURL+(this.verified?'/verified':'/unverified'), {
			method: 'get',
			parameters: 'a2z='+page,
			onSuccess: function(transport) {
				this.data = transport.responseJSON.data;
				this.refresh();
				
				if(Object.isFunction(callback))
					callback.bind(this)();
			}.bind(this)
		});
	},
	
	keyPress: function($super, event)
	{
		if(event.shiftKey && event.keyCode == 86) // v
		{
			event.stop();
			this.toggleVerified();
		}
		else if(event.keyCode == Event.KEY_RETURN || event.keyCode == 89) // y
		{
			if(!this.verified)
			{
				// Verify the current group
				this.groupVerify();
			}
		}
		else if(event.keyCode == 78) // n
		{
			this.groupRemove();
			event.stop();
		}
		else if(event.keyCode == 77) // m
		{
			this.groupsMerge();
			event.stop();
		}
		else
			$super(event);
	},

/**
 * GroupedList#groupsMerge() -> null
 * 
 * Merge the selected groups into one
 **/
	
	groupsMerge: function()
	{
		var selected = this.listView.getSelectedIndexes();
				
		var ids_string = "";
		
		for(var index in selected)
		{					
			if(selected[index])
			{
				ids_string += "&gid[]="+this.data[index].id;
				
				this.listView.list.childElements()[index].setLoading();
			}
		}
		
		var scrollTop = this.listView.surface.scrollTop;
		var selectedElement = this.listView.getSelectedElements()[0].previous().id.split('-').shift();

		new Ajax.Request(window.location.pathname+"ajax/group_merge", {
			method: 'get',
			parameters: ids_string,
			onSuccess: function(transport) {
				console.log(selectedElement);
				this.loadData(this.currentPage, function() {
					this.listView.surface.scrollTop = scrollTop;
					this.listView.selectRow($$("."+transport.responseJSON.data.new_group).shift());
				});
			}.bind(this)
		});
	},

/**
 * GroupedList#groupRemove() -> null
 * 
 * Remove the selected groups
 **/
	
	groupRemove: function()
	{
		var selected = this.listView.getSelectedIndexes();
				
		var ids_string = "";
		
		for(var index in selected)
		{					
			if(selected[index])
			{
				ids_string += "&gid[]="+this.data[index].id;
				
				//this.listView.list.childElements()[index].setLoading();
			}
		}
		
		new Ajax.Request(window.location.pathname+"ajax/group_remove", {
			method: 'get',
			parameters: ids_string,
			onSuccess: function(transport) {
				transport.responseJSON.data.groups.each(function(group){
					$$("."+group.id).each(function(elem){
						elem.setUnVerified();
					}.bind(this));
				});
				
				// Should we refresh the ungrouped list?
				document.fire('group:removed', this.currentPage);
			}.bind(this)
		});
	},

/**
 * GroupedList#groupVerify() -> null
 * 
 * Marked the selected groups as verified
 **/
	
	groupVerify: function()
	{
		var selected = this.listView.getSelectedIndexes();
				
		var ids_string = "";
		
		for(var index in selected)
		{					
			if(selected[index])
			{
				ids_string += "&gid[]="+this.data[index].id;
				
				//this.listView.list.childElements()[index].setLoading();
			}
		}
		
		new Ajax.Request(window.location.pathname+"ajax/group_verify", {
			method: 'get',
			parameters: ids_string,
			onSuccess: function(transport) {
				transport.responseJSON.data.groups.each(function(group){
					$$("."+group.id).each(function(elem){
						elem.setVerified();
					}.bind(this));
				});
			}.bind(this)
		});
	},


/**
 * GroupedList#removeItemFromGroup(item_id, group_id) -> null
 * - item_id (String): The item ID
 * - group_id (String): The group ID
 *  
 * Remove an item from a group
 **/
	
	removeItemFromGroup: function(item_id, group_id)
	{
		var elem = $('grouped-'+item_id);
		
		new Effect.Fade(elem, {
			afterFinish: function(params) {
				var group = params.element.up('li');
				
				if(group.childElements().length == 1)
					group.remove();
				else
					params.element.remove();
			}
		});
				
		new Ajax.Request(window.location.pathname+"ajax/group_removeitem", {
			method: 'get',
			parameters: "id="+item_id+"&gid="+group_id,
			onSuccess: function(transport) {
				// Should we refresh the ungrouped list?
				document.fire('group:removed', this.currentPage);
			}.bind(this)
		});
	},
	
	trashSelectedVerify: function()
	{
		var result = confirm("[GROUPED DELETE] Are you sure you want to delete the selected items from the GROUPED list?");
		
		if(result)
			this.trashSelected();
	},
	
	trashSelected: function()
	{
		var selected = this.listView.getSelectedIndexes();
				
		var ids = new Array();
		
		for(var index in selected)
		{	
			var li = this.listView.list.childElements()[index];
			
			li.childElements().each(function(elem){
				ids.push(elem.id.replace('grouped-', ''));
			});				
			
			li.setLoading();
		}
		
		var ids_string = "";
		ids.each(function(id) {
			ids_string += "&id[]="+id;
		});
		
		var scrollTop = this.listView.surface.scrollTop;
		var selectedElement = this.listView.getSelectedElements()[0].previous().id;
		
		new Ajax.Request(window.location.pathname+"ajax/trash_item", {
			method: 'get',
			parameters: ids_string,
			onSuccess: function(transport) {
				this.loadData(this.currentPage, function() {
					this.listView.surface.scrollTop = scrollTop;
					this.listView.selectRow($(selectedElement));
				});
				document.fire("trash:reload");
			}.bind(this)
		});
	},
	
	updateTitle: function()
	{
		this.titleBar.update(Builder.node('div', {}, [
			"Grouped "+this.currentPage.toUpperCase()+"'s ("+this.data.length+" items)"
		]));
	},
	
	getSurface: function()
	{
		return this.surface;
	},
	
	resize: function()
	{
		
	},
	
	singleClick: function($super, event)
	{
		if(event.target.hasClassName('delete'))
		{
			var div = event.target.up();
			var item_id = div.id.split('-').last();
			this.data.removeItemFromGroup(this.data.itemWithID(item_id));
			document.fire('list:refresh');
		}
		else
			$super(event);
	}
});